package com.hitqz.robot.biz.autoInit;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hitqz.robot.api.business.enums.EquipmentEnum;
import com.hitqz.robot.api.business.enums.FormConfigEnum;
import com.hitqz.robot.api.business.event.FormUpdateEvent;
import com.hitqz.robot.api.business.model.vo.form.FormConfigModalVo;
import com.hitqz.robot.api.business.model.vo.form.FormFieldConfigModalVo;
import com.hitqz.robot.api.common.dto.form.FormFieldConfigUpdateDto;
import com.hitqz.robot.api.common.entity.Button;
import com.hitqz.robot.api.common.entity.FormConfig;
import com.hitqz.robot.biz.service.ButtonService;
import com.hitqz.robot.biz.service.FormConfigService;
import com.hitqz.robot.biz.service.FormFieldConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * @author xupkun
 * @date 2024/5/30
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class H2DefaultTableInit implements CommandLineRunner {
    
    private final FormConfigService formConfigService;

    private final ExecutorService customThreadPool;

    private final ButtonService buttonService;
    
    @Override
    public void run(String... args) {
        //按钮
        customThreadPool.submit(buttonService::init);
        //动态表单
        customThreadPool.submit(this::initForm);

    }

    private void initForm(){
        try{
            List<FormConfig> list = formConfigService.list();
            Set<String> formNameSet = list.stream().map(FormConfig::getFormName).collect(Collectors.toSet());
            for (FormConfigEnum value : FormConfigEnum.values()) {
                if (formNameSet.isEmpty() || !formNameSet.contains(value.getFormName())){
                    // 如果没有则,创建表单默认值
                    formConfigService.createDefaultFormFieldConfig(value);
                }
            }
            //机器人参数 发布事件
            FormConfigModalVo formModal = formConfigService.getFormModal(FormConfigEnum.ROBOT_PARAMS_CONFIG.getFormName());
            List<FormFieldConfigUpdateDto> updateFields = new ArrayList<>();
            for (FormFieldConfigModalVo field : formModal.getFields()) {
                updateFields.add(new FormFieldConfigUpdateDto(field.getName(), field.getCurrentValue(), field.getCurrentValue()));
            }
            if (!updateFields.isEmpty()) {
                //监听事件的地方要自己判断机器人嵌入式或控制器是否在线，不在线则延时再去设置本体参数
                SpringUtil.getApplicationContext().publishEvent(new FormUpdateEvent(FormConfigEnum.ROBOT_PARAMS_CONFIG.getFormName(), updateFields));
                log.info("发布机器人参数设置事件");
            }
        }catch (Exception e){
            log.error("创建默认表数据",e);
        }
    }





}
